将某个时间以固定格式转化为字符串

表示日期格式的工具类:java.text.SimpleDateFormat
日期->文本:格式化format();
文本->日期:解析
在创建SimpleDateFormat时,需要指定格式,如
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
String str = sdf.format(date);

1
2
3
4
5
6
7
8
9
10
11
12
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) {
Date date = new Date();
System.out.println(date2FormatStr(date));
}
public static String date2FormatStr(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
}

输出:

1
2018-08-22 21:33:05